<template>
  <div class="brandList-container">
    <search-form
      :config-list="searchFormConfig"
      @search="search"
      @reset="reset"
      ref="searchFormRef"
    >
      <template #leftSlot>
        <!--左侧的插槽-->
        <el-button
          icon="Search"
          type="primary"
          @click="batchSettlement"
          v-permissions="['salesManbatchSettlement']"
        >
          批量结算
        </el-button>
      </template>
      <template #rightSlot>
        <!--右侧的插槽-->
      </template>
    </search-form>
    <CustomTable
      :pagination="pagination"
      :table-config="tableConfig"
      @pagination-change="paginationChange"
      @actions-click="actionsClick"
      @selection-change="selectionChange"
    />
  </div>
</template>

<script>
  export default {
    name: 'salesmanList',
  }
</script>

<script setup>
  import CustomTable from '@/views/component/CustomTable'
  import SearchForm from '@/views/component/SearchForm' //引入搜索组件
  import {
    getSalesmanList as getList,
    settlement,
    batchSettlement as batchSettlementApi,
    settlementBack
  } from '~/src/api/salesman'
  import { message } from '@/utils/helper'
  // 搜索参数
  const queryForm = ref({})

  const tableConfig = reactive({
    isSelect: true,
    columns: [
      {
        label: 'ID',
        prop: 'id',
        sortable: false,
        width: 90,
      },
      { label: '店铺名称', prop: 'shop_name', sortable: false, width: 180 },
      {
        label: '订单号',
        prop: 'order_sn',
        sortable: false,
        width: 210,
      },
      {
        label: '业务员',
        prop: 'sales_person_name',
        sortable: false,
        width: 160,
      },
      {
        label: '下单金额',
        prop: 'order_amount',
        sortable: false,
        width: 150,
      },
      {
        label: '提成金额',
        prop: 'commission_amount',
        sortable: false,
        width: 150,
      },
      {
        label: '结算状态',
        prop: 'status',
        sortable: false,
        width: 120,
        customType: 'ElTag',
        tagKeyValue: 'statusTag',
      },
      {
        label: '结算时间',
        prop: 'completion_time',
        sortable: false,
        width: 180,
      },
      {
        label: '创建时间',
        prop: 'order_create_time',
        sortable: false,
        width: 180,
      },
      {
        label: '操作',
        action: true,
        fixed: 'right',
        actions: [
          {
            fnName: 'Settlement',
            title: '结算',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'salesManSettlement', // 权限
            key: 'status',
            showValue: 1,
          },
          {
            fnName: 'withdraw',
            title: '撤回',
            type: 'danger',
            isTextBtn: true,
            permissionCode: 'withdrawSettlement', // 权限
            key: 'status',
            showValue: 2,
          },
        ],
      },
    ],
    tagConfig: {
      storeTag: {
        1: {
          name: '小林',
          type: 'success',
        },
      },
      //审批状态 1:审批中 2:审批通过 3:审核不通过
      statusTag: {
        1: {
          name: '待结算',
          type: 'success',
        },
        2: {
          name: '已结算',
          type: 'primary',
        },
      },
    },
    list: [],
    listLoading: false,
  })

  //搜索组件配置信息
  const searchFormConfig = reactive({
    config: {
      layoutType: 1, //1:左右布局,2:上下布局
      leftPanelWidth: 0, //控制左边布局控件宽度
    },
    controlList: [
      { label: '店铺名称', prop: 'shop_name', type: 'input' },
      { label: '订单号', prop: 'order_sn', type: 'input' },
      {
        label: '业务员名称',
        prop: 'sales_person_name',
        type: 'input',
      },
      {
        label: '结算状态',
        prop: 'status',
        type: 'select',
        list: Object.keys(tableConfig['tagConfig']['statusTag']).reduce(
          (acc, cur) => {
            const { name } = tableConfig['tagConfig']['statusTag'][cur]
            acc.push({ label: name, value: cur })
            return acc
          },
          []
        ),
      },
    ],
  })

  //点击搜索触发
  const search = (form) => {
    console.log(form)
    pagination.page = 1
    queryForm.value = form
    queryProject()
  }

  //列表分页参数
  const pagination = reactive({
    page: 1, //每页条数
    limit: 10, //当前页
    total: 0,
    layout: 'total, sizes, prev, pager, next, jumper',
  })

  //分页控件点击操作
  const paginationChange = (data) => {
    const { val, type } = data
    pagination[type] = val
    queryProject()
  }

  //请求列表数据
  const queryProject = () => {
    tableConfig.listLoading = true
    getList({
      ...queryForm.value,
      limit: pagination.limit,
      page: pagination.page,
    })
      .then((result) => {
        console.log('result', result)
        tableConfig.list = result.data.data
        tableConfig.listLoading = false
        pagination.total = result.data.total
      })
      .catch(() => {
        tableConfig.listLoading = false
      })
  }

  //点击表格操作按钮回调
  const actionsClick = (data) => {
    console.log('actionsClick===', data)
    const { type, row } = data
    switch (type) {
      case 'Settlement':
        handleSettlement(row)
        break
      case 'withdraw':
        handleWithdraw(row)
        break
    }
  }
  const handleSettlement = (row) => {
    ElMessageBox.confirm(
      '您确定线下已跟业务员结算，点击“确定”后提成单变成已结算？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      await settlement({
        id: row.id,
        status: 2,
      })
      message('结算成功')
      queryProject()
    })
  }

  const handleWithdraw = (row) => {
    ElMessageBox.confirm(
      '您确定要回退该条记录,点击“确定”将回退到待结款状态？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      await settlementBack({ id: row.id })
      message('结算成功')
      queryProject()
    })
  }

  const searchFormRef = ref(null)
  const reset = () => {
    if (!searchFormRef.value) return
    searchFormRef.value.resetFormFields()
    queryProject()
  }

  const init = async () => {
    await queryProject()
  }
  const batchSettlement = () => {
    if (selectRows.value.length === 0)
      return message('请选择要结算的提成单', 'error')
    ElMessageBox.confirm(
      '您确定线下已跟业务员结算，点击“确定”后提成单批量变成已结算？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const arr = selectRows.value.filter((item) => item.status == 1)
      if (arr.length === 0)
        return message('全部都是已结算状态，无需结账', 'error')
      await batchSettlementApi({
        id: arr.map((item) => item.id),
        status: 2,
      })
      message('批量结算成功')
      await queryProject()
    })
  }

  const selectRows = ref([])
  const selectionChange = (val) => {
    selectRows.value = val
  }
  onMounted(() => {
    init()
  })
</script>

<style lang="scss" scoped></style>
